<?php

class Admin extends Controller{
	
	private $identities=array();
	
	public $autoRender = false;
	
	private $DIR_USERIMAGES = "resource/image/userimages";
	private $IMAGE_EXTENSIONS = array("jpg", "jpeg", "png", "gif");
	private $IMAGE_SIZES = array(
		"thumb" => array(75,75),
		"normal" => array(200,200),
		"large" => array(400,400)
	);
	
	public function __construct(){
		//load identities
		foreach (file("lib/identities") as $identity){
			list($username,$password) = explode(":", $identity, 2);
			$this->identities[$username] = trim($password);
		}
		
		parent::__construct();
	}
	
	public function index(){
		if(!$_SESSION["user"]){
			$this->render("admin/login");
		}else{
			redirect();
		}
	}
	
	public function login(){
		$username = $_POST["username"];
		$password = $_POST["password"];
		
		if(isset($this->identities[$username]) && md5($password) == $this->identities[$username]){
			$_SESSION["user"] = $username;
		}else{
			$this->flashSet(__("Anmeldung fehlgeschlagen.",true), "error");
		}
		
		redirect("/admin");
	}
	
	public function logout(){
		unset($_SESSION["user"]);
		redirect();
	}
	
	public function page_edit(){
		$page = $_POST["page"];
		$data = array(
			"name" => $page,
			"html" => array()
		);
		foreach ($this->langs as $key=>$label){
			$filename = "app/views/seite/$key/$page.ctp";
			if(file_exists($filename)){
				$data["html"][$key] = file_get_contents($filename);
			}else{
				$data["html"][$key] = "";
			}
		}
		$this->set("page", $data);
		$this->layout = false;
		$this->render();
	}
	
	public function page_save(){
		$page = $_POST["page"];
		$name = $page["name"];
		$written = 0;
		if($page && $name){
			foreach ($page["html"] as $lang=>$html){
				$written += file_put_contents("app/views/seite/$lang/$name.ctp", trim($html));
			}
		}
		ob_clean();
		header("X-Status: ".$written);
		__($written>0 ? "Seite gespeichert" : "Seite nicht gespeichert");
	}
	
	public function userimages(){
		$dir = opendir($this->DIR_USERIMAGES);
		$images = array();
		while($f = readdir($dir)){
			$ext = strtolower(substr($f, strrpos($f, ".")+1));
			if(in_array($ext, $this->IMAGE_EXTENSIONS)){
				$images[] = $f;
			}
		}
		echo json_encode($images);
	}
	public function userimage_show($size,$name){
		$dimensions = $this->IMAGE_SIZES[$size];
		$w = $dimensions[0];
		$h = $dimensions[1];
		error_reporting(E_ALL);
		ini_set("display_errors", "On");
		$img = Image::img_create("{$this->DIR_USERIMAGES}/$name");
		Image::img_resize($img, $w, $h);
		Image::img_throw($img, $name);
	}
	public function userimage_upload(){
		$image = $_FILES["userimage"];
		if(!$image["error"]){
			
			$ext = strtolower(substr($image["name"], strrpos($image["name"], ".")+1));
			if(in_array($ext, $this->IMAGE_EXTENSIONS)){
				$destination = $this->DIR_USERIMAGES."/".$image["name"];
				if(move_uploaded_file($image["tmp_name"], $destination)){
					__("Das Bild hochgeladen");
				}
			}else{
				echo __("Error", true)."! ".__("Ausgewähltes Bild ist kein Bild", true);
			}
		}else{
			echo __("Error", true) ."! " . __("Das Bild nicht hochgeladen", true) . ".";
		}
	}
	public function userimage_delete($name){
		$status = 0;
		if(!unlink($this->DIR_USERIMAGES."/$name")){
			$status = 1;
		}
		header("X-Status: $status");
	}
	
	public function kontakt(){
		$name = $_POST["name"];
		$email = $_POST["email"];
		$text = $_POST["message"];
		$captcha = $_POST["captcha"];
		
		$status = 0;
		$ret = __("Poruka je uspešno prosleđena", true);
		
		
		$to = CONTACT_EMAIL;
		$subject = "Kontakt sa sajta: $name";
		$message = "<h1>$name <$email></h1>".nl2br($text);
		$headers = "Content-Type: text/html;charset=utf-8\r\n"
				  ."From: \"$name\"<$email>\r\n";
		
		if(!$name || !$email || !$text || !$captcha){
			$status = 1;
			$ret = __("Morate popuniti sva polja", true);
		}elseif (!is_email($email)){
			$status = 1;
			$ret = __("E-Mail adresa nije validna", true);
		}elseif(strtolower($captcha)!=strtolower($_SESSION["kapca"])){
			$status = 1;
			$ret = __("Uneti tekst nije isti kao sigurnosni tekst sa slike", true);
		}elseif(!mail($to, $subject, $message, $headers)){
			$status = 1;
			$ret = __("Poruka nije prosleđena", true);
		}
		
		$this->set("data", array(
			"name" => $name,
			"email" => $email,
			"message" => $text,
			"captcha" => $captcha
		));
		$this->set("status_code", $status ? "error" : "ok");
		$this->set("status_message", $ret);
		$this->render("page/contact");
	}
	public function kontakt_captcha(){
		$buffer = "qwertyuiopasdfghjklzxcvbnm0123456789";
		$ret = "";
		for($i=0; $i<7; $i++){
			$ret .= substr($buffer, rand(0, strlen($buffer)-1), 1);
			
		}
		error_reporting(E_ALL);ini_set("display_errors", "On");
		$w = 100; $h = 30;
		$img = imagecreatetruecolor($w,$h);
		$color = imagecolorallocate($img, 222, 210, 178);
		$background = imagecolorallocate($img, 255, 255, 255);
		imagefilledrectangle($img, 0, 0, $w, $h, $background);
		
		$font = "resource/cambriab.ttf";
		$size = 14;
		$bbox = imagettfbbox($size, 0, $font, $ret);
		
		$x = ($w-$bbox[2]+$bbox[0])/2;
		$y = ($h-$bbox[5]+$bbox[3])/2;
		
		imagettftext($img, $size, 0, $x, $y, $color, $font, $ret);
		
		$_SESSION["kapca"] = $ret;
		header("Content-Type: image/png; filename=captcha.png");
		imagepng($img);
	}
}